package com.briup.jd2511.jd2511bookstore.controller;


import com.briup.jd2511.jd2511bookstore.pojo.User;
import com.briup.jd2511.jd2511bookstore.pojo.dto.UserPageDto;
import com.briup.jd2511.jd2511bookstore.pojo.vo.UserPageVO;
import com.briup.jd2511.jd2511bookstore.response.Result;
import com.briup.jd2511.jd2511bookstore.service.UserService;
import com.briup.jd2511.jd2511bookstore.utils.JwtUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Tag(name = "用户管理模块接口")
@RestController
@Scope("prototype")
@Lazy
@RequestMapping("/users")
public class UserController {

	@Resource
	private UserService userService;

	// 提供空参构造器
	public UserController() {
		System.out.println("userController 被创建啦。。。");
	}

	@Operation(summary = "分页多条件查询用户信息")
	@GetMapping
	public Result<PageInfo<UserPageVO>> list(UserPageDto userPageDto) {
		log.info("分页多条件查询用户数据:{}", userPageDto);
//		log.debug("debug test");
//		log.warn("warn test");
//		log.error("error test");
		System.out.println(userService.getClass().getName());
		return Result.success(userService.getUsersPageByConditional(userPageDto));
	}

	@Operation(summary = "删除用户")
	@DeleteMapping("/{ids}")
	public Result<String> deleteUsers(@PathVariable("ids") List<Integer> ids) {
		log.info("删除用户:{}", ids);
		userService.deleteUsers(ids);
		return Result.success();
	}

	@Operation(summary = "添加用户")
	@PostMapping
	public Result<String> saveUser(@RequestBody User user) throws Exception {
		log.info("添加用户:{}", user);
		userService.addUser(user);
		return Result.success();
	}

	@Operation(summary = "根据id查询单个用户")
	@GetMapping("/{id}")
	public Result<User> getUser(@PathVariable Integer id) {
		log.info("根据id查询用户:{}", id);
		return Result.success(userService.getUserById(id));
	}

	@Operation(summary = "修改用户")
	@PutMapping
	public Result<String> updateUser(@RequestBody User user) {
		log.info("修改用户:{}", user);
		userService.updateUser(user);
		return Result.success();
	}

	@Operation(summary = "查询单个用户")
	@GetMapping("/getUserInfo")
	public Result<User> getUserInfo(HttpServletRequest request) {

		log.info("查询当前登录的用户信息");
		// 获取请求头token的值
		String token = request.getHeader("token");
		// 解析token字符串
		Integer userId = JwtUtil.getUserId(token);
		return Result.success(userService.getUserById(userId));
	}
}
